<template>
  <el-drawer
    v-model="visible"
    append-to-body
    :title="title || '无标题'"
    modal-class="EditInstructionDrawer"
    @close="() => emits('visibleChange', false)"
  >
    <div class="drawerContent">
      <el-form
        :model="postForm"
        class="form"
        label-width="130px"
        label-position="right"
        ref="formRef"
      >
        <el-form-item label="指令版本：" prop="version" required>
          <el-checkbox-group v-model="postForm.version">
            <el-checkbox :label="2">中小学</el-checkbox>
            <el-checkbox :label="1">大学</el-checkbox>
            <el-checkbox :label="4">中职</el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="返回内容：" prop="content" required>
          <el-input
            v-model="postForm.content"
            type="textarea"
            class="textArea"
          />
        </el-form-item>

        <div class="isOpen">
          <el-form-item label="是否直接启用">
            <el-switch v-model="postForm.flag" />
          </el-form-item>
          <span
            >确保各项数据正确时可直接启用，否则建议由管理员再次确认后再启用。</span
          >
        </div>
      </el-form>
      <div class="buttons">
        <el-form-item>
          <el-button type="primary" @click="onSubmit">确认 </el-button>
          <el-button
            @click="
              () => {
                visible = false;
                emits('visibleChange', false);
              }
            "
          >
            取消
          </el-button>
        </el-form-item>
      </div>
    </div>
  </el-drawer>
</template>

<script setup>
import {
  api_addWorkBook,
  api_updateWorkBook,
  checkSameInstructName,
  getAllSystemInfo,
} from "@/api/manage";
import { computed, onMounted, reactive, ref, watch } from "vue";
import { useRoute } from "vue-router";
import { getSubSystemsMainServerBySubjectID } from "../../../utils/CommonRequest";

const route = useRoute();
const props = defineProps({
  show: Boolean,
  title: String,
  defaultInfo: Object,
});

const emits = defineEmits(["visibleChange", "submitSuccess"]);

const instructTypeList = [
  { label: "打开操作", value: "OPEN_OPERATION" },
  { label: "数据返回", value: "DATA_RETURN" },
  { label: "控制操作", value: "CONTROL_OPERATION" },
];

const visible = ref(props.show);

const formRef = ref();

const postForm = reactive({
  instructCode: "",
  instructName: "",
  content: "",
  version: [],
  flag: false,
});

const voiceArr = ref([]);
const dragListRef = ref(null);

const rawSysInfos = ref([]);
const sysInfos = computed(() => {
  return rawSysInfos.value?.map((v) => ({
    label: `${v.sysName}(${v.sysId})`,
    value: v.sysId,
  }));
});
onMounted(() => {
  // getAllSystemInfo(route.query?.schoolId ?? "")
  //   .then((res) => {
  //     const { data, success, msg } = res;
  //     if (!success) {
  //       ElMessage.error("获取全部系统ID失败,接口返回:" + msg);
  //       return;
  //     }
  //     rawSysInfos.value = data;
  //   })
  //   .catch((e) => {
  //     ElMessage.error("获取全部系统ID失败");
  //   });
});
const init = () => {
  getAllSystemInfo()
    .then((res) => {
      const { data, success, msg } = res;
      if (!success) {
        ElMessage.error("获取全部系统ID失败,接口返回:" + msg);
        return;
      }
      rawSysInfos.value = data;
    })
    .catch((e) => {
      ElMessage.error("获取全部系统ID失败");
    });
};
defineExpose({ init });

// 是否显示有相同指令提示语
const hasSameInstructName = ref(false);
const checkInstructName = async () => {
  if (!postForm.instructName) {
    return;
  }
  const { data, success } = await checkSameInstructName({
    instructName: postForm.instructName,
  });
  if (!success) {
    ElMessage.error("判断是否有重复指令名称请求失败");
  }
  if (data) {
    hasSameInstructName.value = true;
  } else {
    hasSameInstructName.value = false;
  }
};

watch(
  () => props.show,
  (newVale) => {
    visible.value = newVale;
    hasSameInstructName.value = false;
  }
);
const EVersionTextMap = {
  1: [1],
  2: [2],
  3: [1, 2],
  4: [4],
  5: [1, 4],
  6: [2, 4],
  7: [1, 2, 4],
};
/*
  instructCode: "",
  instructName: "",
  content: "",
  version: [],
  flag: false
  */
const initDefaultInfo = (defaultInfo) => {
  if (!defaultInfo) {
    voiceArr.value = [];
    Object.assign(postForm, {
      instructCode: "",
      instructName: "",
      content: "",
      version: [],
      flag: false,
    });
    return;
  }
  Object.assign(postForm, {
    instructCode: defaultInfo.instructCode,
    instructName: defaultInfo.instructName,
    content: defaultInfo.content,
    version: EVersionTextMap[defaultInfo.version],
    flag: defaultInfo.flag === 0 ? true : false,
    id: defaultInfo.id,
  });
};

watch(
  () => props.defaultInfo,
  (newVal) => {
    initDefaultInfo(newVal);
  },
  { deep: true }
);

watch(
  () => props.show,
  (newVal) => {
    if (!newVal) return;
    initDefaultInfo(props.defaultInfo);
  }
);

watch(
  () => postForm.sysId,
  async (newVal) => {
    if (!newVal) {
      return;
    }
    postForm.instructSource =
      rawSysInfos.value.find((v) => v.sysId === newVal)?.sysName ?? "";
    const { ErrCode, Data } = await getSubSystemsMainServerBySubjectID(newVal);
    if (ErrCode !== 0) {
      ElMessage.error("基础平台获取服务器地址失败");
      return;
    }
    postForm.openUrl = Data?.[0]?.WebSvrAddr ?? "";
  },
  {
    immediate: true,
  }
);
watch(
  () => props.show,
  async (newVal) => {
    if (!newVal || !postForm.sysId) {
      return;
    }
    postForm.instructSource =
      rawSysInfos.value.find((v) => v.sysId === postForm.sysId)?.sysName ?? "";
    const { ErrCode, Data } = await getSubSystemsMainServerBySubjectID(
      postForm.sysId
    );
    if (ErrCode !== 0) {
      ElMessage.error("基础平台获取服务器地址失败");
      return;
    }
    postForm.openUrl = Data?.[0]?.WebSvrAddr ?? "";
  },
  {
    immediate: true,
  }
);

const onSubmit = async () => {
  try {
    await formRef.value?.validate();
  } catch {
    return;
  }
  console.log("postForm = ", postForm);
  const requestInfo = { ...postForm };
  requestInfo.flag = requestInfo.flag;

  requestInfo.version = postForm.version.reduce((res, i) => (res += i), 0);
  requestInfo.flag = requestInfo.flag ? 0 : 1;

  requestInfo.version = String(requestInfo.version);
  console.log("requestInfo = ", requestInfo);
  if (props.title.indexOf("新增") != -1) {
    requestInfo.id = "123";
    const res = await api_addWorkBook(requestInfo);
    if (res.success === true) {
      visible.value = false;
      emits("visibleChange", false);
      emits("submitSuccess");
      ElMessage.success("请求成功");
    } else {
      ElMessage.error("请求失败,接口返回:" + res.msg);
    }
  } else {
    const res = await api_updateWorkBook(requestInfo);
    if (res.success === true) {
      visible.value = false;
      emits("visibleChange", false);
      emits("submitSuccess");
      ElMessage.success("请求成功");
    } else {
      ElMessage.error("请求失败,接口返回:" + res.msg);
    }
  }
};
</script>

<style lang="scss">
body {
  .EditInstructionDrawer {
    position: fixed;
    .el-drawer {
      width: 963px !important;
    }
  }
}
</style>
<style lang="scss" scoped>
.drawerContent {
  position: relative;
  min-height: 100%;
  padding-bottom: 30px;

  .form {
    :deep(.el-form-item .el-form-item__label) {
      font-size: 15px;
      color: #333;
    }
    :deep(.el-textarea__inner) {
      height: 400px;
    }
    .topFlex {
      display: flex;
      gap: 25px;
    }
    .second {
      display: flex;
      .id {
        display: flex;
        gap: 5px;
        .info {
          position: relative;
          top: 5px;
          width: 20px;
          height: 20px;
        }
      }
    }
    .openUrl {
      display: flex;
      gap: 5px;
      .info {
        position: relative;
        top: 5px;
        width: 20px;
        height: 20px;
      }
    }
    .flexVersion {
      display: flex;
      justify-content: flex-start;
      gap: 25px;
      & info {
        position: relative;
        top: 5px;
        width: 20px;
        height: 20px;
      }
    }
    .voicesWrapper {
      .voices {
        display: flex;
        flex-direction: column;
        gap: 10px;
      }
      .voiceItem {
        display: flex;
        justify-content: flex-start;
        gap: 10px;
        .voiceCommandsHandler {
          width: 10px;
          height: 32px;
          background-color: #eee;
          cursor: move;
        }
        .input {
          width: 500px;
        }
        & .add,
        .delete {
          position: relative;
          top: 3px;
          width: 25px;
          height: 25px;
          &:hover {
            cursor: pointer;
          }
        }
      }
    }
    .isOpen {
      display: flex;
      gap: 10px;
      span {
        font-size: 14px;
        line-height: 30px;
        color: #999;
      }
    }
  }

  .buttons {
    position: absolute;
    bottom: -20px;
    right: 50px;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 20px;
    :deep(.el-button) {
      width: 100px;
      height: 35px;
    }
  }
}
</style>
